package mqLog

import (
	"duanju-mq/pkg/config"
	"duanju-mq/pkg/log"
	fileLog "duanju-mq/pkg/util/mqLog/filelog"
	uTime "duanju-mq/pkg/util/time"
	"os"
	"path/filepath"
	"time"
)

var (
	logFileList = []*logFileInfo{}
)

type logFileInfo struct {
	FileName          string
	FileLogStatus     bool
	FileLogTarStatus  bool
	FileLogReserveDay int
	FileNamePrefix    string
	FileLogger        *fileLog.Logger
}

func init() {
	loadLogFileConfig()
	config.OnReload(loadLogFileConfig)
}

func loadLogFileConfig() {
	for _, info := range logFileList {
		info.FileLogStatus = false
	}
	logFileList = []*logFileInfo{}
	config.Sequence("logFile.fileList", "logFile fileList ", func(cfg *config.SeqCfg) {
		prefix := *cfg.String("prefix", "", "logFile prefix")
		logStatus := *cfg.Bool("logStatus", true, "logFile status")
		tarStatus := *cfg.Bool("tarStatus", false, "mq log tar status")
		logReserveDay := *cfg.Int("reserveDay", 90, "reserveDay")

		logInfo := &logFileInfo{
			FileLogStatus:     logStatus,
			FileLogTarStatus:  tarStatus,
			FileNamePrefix:    prefix,
			FileLogReserveDay: logReserveDay,
			FileLogger:        fileLog.NewLogger(),
		}
		logFileList = append(logFileList, logInfo)

		go logInfo.checkLogFileName()
	})
}
func (t *logFileInfo) checkLogFileName() {
	for {
		if !t.FileLogStatus {
			break
		}
		time.Sleep(time.Second)
		if name := t.getLogFileName(); name != t.FileName {
			t.FileName = name
			if wc, err := fileLog.GetWriteIO(t.FileName); err == nil {
				fileLog.SetOutput(t.FileLogger, wc)
			} else {
				t.FileName = ""
				log.Err("GetWriteIO err:", err)
			}
		}
	}
}

func (t *logFileInfo) getLogFileName() string {
	nt := time.Now()
	logDir := filepath.Join(*logFileDir, uTime.FmtDate(nt, "Ym"))
	exist, _ := PathExists(logDir)
	if !exist {
		os.Mkdir(logDir, os.ModePerm)
	}
	return filepath.Join(logDir, t.FileNamePrefix+uTime.FmtDate(nt, "Ymd")+".log")
}

func (t *logFileInfo) WriteLog(s string) {
	if t.FileLogStatus {
		fileLog.WriterString(t.FileLogger, s)
	}
}
